package com.wyb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyb.mapper.ArticleMapper;
import com.wyb.mapper.UserMapper;
import com.wyb.pojo.Article;
import com.wyb.constant.Result;
import com.wyb.service.ArticlePageService;
import com.wyb.utils.JwtUtil;
import com.wyb.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticlePageServiceImpl implements ArticlePageService {
    @Autowired
    public ArticleMapper articleMapper;
    @Autowired
    public UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Result articlePages(int index, int pagesize, int categoryId, String token) {

        //获取文章分页数据
        IPage page = new Page(index,pagesize);
        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper();
        lqw.orderByDesc(Article::getIsTop);
        lqw.orderByDesc(Article::getCreateTime);
        if(categoryId!=0){
                    lqw.eq(Article::getCategoryId,categoryId);
        }
        IPage iPage = articleMapper.selectPage(page, lqw);
        List<Article> articles = iPage.getRecords();
        Map<String,Object> map = new HashMap<String,Object>();
        if(StringUtils.hasText(token)&&!token.equals("null")){
            //获取用户ID
            String userId;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userId = claims.getSubject();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(token);
                throw new RuntimeException("token非法");
            }
            for (Article article: articles) {
                boolean like = redisCache.isMemory("ariticle_liked_key"+article.getId(), userId);
                if(like){
                    article.setIsLiked(1);
                }else {
                    article.setIsLiked(0);
                }
                boolean unliked = redisCache.isMemory("ariticle_unliked_key"+article.getId(), userId);
                if(unliked){
                    article.setIsUnliked(1);
                }else {
                    article.setIsUnliked(0);
                }
            }
        }

        map.put("articles", articles);
        map.put("total", iPage.getTotal());
        return new Result(200,"第"+index+"页内容成功查询",map);
    }

}
